#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2023/9/10 2:30
# @Author  : BadMan
# @FileName: Set_num_info_pdf.py
from PyPDF2 import PdfFileReader, PdfFileWriter
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
# 打开合并后的 PDF 文件
input_pdf_path = './image_paths/pdf_files/new_merged_pdf/merged.pdf'
pdf_reader = PdfFileReader(input_pdf_path)
# 创建一个新的 PDF 文件对象
output_pdf_path = './image_paths/pdf_files/new_merged_pdf/modified_set_info.pdf'
pdf_writer = PdfFileWriter()


start_page = 3
end_page = 6

count = 0
# 复制输入文件的所有页面到输出文件
for page_num in range(pdf_reader.getNumPages()):
    page = pdf_reader.getPage(page_num)
    # 在第四页上添加标记
    if start_page <= page_num + 1 <= end_page:
        count  = count + 1
        print(count)
        c = canvas.Canvas(f"{count}.pdf", pagesize=letter)
        width, height = letter
        text = fr"{count}"
        text_width = c.stringWidth(text, "Helvetica", 12)  # Kuan
        text_height = 50  # 设置标记位置距离底部的高度
        c.setFont("Helvetica", 12)  # 大小
        c.setFillColorRGB(1, 0, 0)  # 设置字体颜色为 hongse
        c.drawString((width - text_width) / 2, text_height, text)
        c.save()
        temp_pdf = PdfFileReader(f"{count}.pdf")

        # page.mergePage(temp_pdf.getPage(0))
        temp_page = temp_pdf.getPage(0)
        temp_page.scaleTo(page.mediaBox.getWidth(), page.mediaBox.getHeight())  # 将临时页面大小调整为原页面大小
        page.mergePage(temp_page)  # 将临时页面的内容合并到原页面
        # pdf_writer.addPage(page)
    pdf_writer.addPage(page)
# 将修改后的 PDF 文件保存到新的文件夹中
with open(output_pdf_path, "wb") as output_file:
    pdf_writer.write(output_file)

print(f"修改成功，保存为 {output_pdf_path}")